package com.lysj.bhp.withdraw.service;

import com.lysj.bhp.util.json.JacksonUtil;
import com.lysj.bhp.withdraw.base.WithdrawContent;
import com.lysj.bhp.withdraw.contract.Bhpc;
import com.lysj.bhp.withdraw.domain.WithDraw;
import com.lysj.bhp.withdraw.repository.WithdrawRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.web3j.crypto.CipherException;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.Contract;
import org.web3j.tx.ManagedTransaction;
import org.web3j.utils.Convert;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

@Service
@Transactional
public class BhpcTransactionService extends WithdrawContent {

    private static Logger logger = LoggerFactory.getLogger(BhpcTransactionService.class);

    @Resource
    private Web3j web3j;
    @Resource
    private WithdrawRepository withdrawRepository;

    /**
     * 提交转币的任务(秘钥模式)
     *
     * @return
     */
    public boolean submitBhpcTransactionOfPrivkey(WithDraw withDraw) {

        String myMetamaskPrivKey = "ef7d98d637eb0bfe120250b6bc5f47876db09ceb462c298e39d70781ffaba166";  //0xEC8ad444cC459d2Ec9E513d0af41b3Bad2c56958

        String myKeystorePath = "D:\\temp\\UTC--2018-05-18T09-53-15.586000000Z--01bbb6578f76816aee8f03bfabdd1178f059363e.json";
        String myKeystorePsw = "BEF463C208A047E8B063A068652C8ED5";


        // 获取发送方账号凭证
//        ECKeyPair ecKeyPair = ECKeyPair.create(new BigInteger(myMetamaskPrivKey, 16));
//        Credentials credentials = Credentials.create(ecKeyPair);

        Credentials credentials = null;
        try {
            credentials = WalletUtils.loadCredentials(myKeystorePsw, myKeystorePath);
        } catch (IOException | CipherException e) {
            e.printStackTrace();
        }

        Bhpc token = Bhpc.load(ETH_BHPC_CONTRACT_ADDRESS, web3j, credentials, ManagedTransaction.GAS_PRICE, Contract.GAS_LIMIT);

        new Thread(() -> {
            try {
                TransactionReceipt transferReceipt = token
                        .transfer(withDraw.getAddress(), Convert.toWei(withDraw.getAmount().subtract(withDraw.getFeeAmount()), Convert.Unit.ETHER).toBigInteger())
                        .send();
                logger.info("本次交易回复:" + JacksonUtil.toJson(transferReceipt));
                withDraw.setTransctionStatus(1);
                withDraw.setTxHash(transferReceipt.getTransactionHash());
                withdrawRepository.save(withDraw);
            } catch (InterruptedException | ExecutionException e) {
                logger.error(e.getMessage());
                logger.error("发起代币交易出现异常");
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();

        return true;
    }


}
